package com.gy.api.sms.service;

import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.gy.api.sms.config.ServiceConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class DynamicMessageService {

    @Autowired
    private ServiceConfig config;

    /**
     * 获取 accessToken
     *
     * @return
     * @throws Exception
     */
    private String getAccessToken() throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(config.getTokenUrl());
            JSONObject json = new JSONObject();
            json.put("grant_type", "client_credentials");
            json.put("client_id", config.getClientId());
            json.put("client_secret", config.getClientSecret());

            StringEntity entity = new StringEntity(json.toString());
            post.setEntity(entity);
            post.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse response = client.execute(post)) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject responseJson = new JSONObject(result);
                return responseJson.getStr("access_token");
            }
        }
    }

    /**
     * 根据模板ID来发送动态短信
     *
     * @param businessName
     * @param mobile
     * @param params
     * @throws Exception
     */
    public void sendDynamicMessage(String businessName, String mobile, Map<String, String> params) throws Exception {
        String accessToken = getAccessToken();
        String templateId = config.getTemplateMap().get(businessName);

        if (templateId == null) {
            throw new IllegalArgumentException("没有对应的短信模板 " + businessName);
        }

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(config.getDynamicMessageUrl());
            JSONObject dynamicParams = new JSONObject(params);

            JSONObject message = new JSONObject();
            message.put("chatBotId", config.getChatbotId());
            message.put("mobiles", new JSONArray().put(mobile));
            message.put("templateId", templateId);
            message.put("dynamicParams", dynamicParams);

            JSONArray jsonArray = new JSONArray();
            jsonArray.put(message);

            StringEntity entity = new StringEntity(jsonArray.toString(), "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Authorization", "Bearer " + accessToken);

            try (CloseableHttpResponse response = client.execute(post)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("响应的状态:" + statusCode);
                System.out.println("响应的内容:" + result);

                if (statusCode == 200) {
                    System.out.println("短信发送成功");
                } else {
                    System.err.println("发送短信失败:" + result);
                }
            }
        }
    }



    private static final String SMS_CLIENT_ID="551b4bc88b0f54bebb512cb262b50e7d";
    private static final String SMS_CLIENT_SECRET="314b119b6d486d2ea0287b49926162a3";
    private static final String SMS_TOKEN_URL="https://api.yitd.cn/auth/token";
    private static final String SMS_SEND_URL="https://api.yitd.cn/sauth/multiUTF8";
    private static final String SMS_ACCOUNT="683023";
    private static final String SMS_PASSWORD="kkzxVP";


    private String  getSmsAccessToken() throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(SMS_TOKEN_URL);
            JSONObject json = new JSONObject();
            json.put("grant_type", "client_credentials");
            json.put("client_id", SMS_CLIENT_ID);
            json.put("client_secret", SMS_CLIENT_SECRET);

            StringEntity entity = new StringEntity(json.toString());
            post.setEntity(entity);
            post.setHeader("Content-Type", "application/json");

            try (CloseableHttpResponse response = client.execute(post)) {
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("响应的状态:" +  response.getStatusLine().getStatusCode());
                System.out.println("响应的内容:" + result);
                JSONObject responseJson = new JSONObject(result);
                return responseJson.getStr("access_token");
            }
        }
    }


    public void sendDynamicMessage(String content, String mobile) throws Exception {
        String accessToken = getSmsAccessToken();
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(SMS_SEND_URL);

            JSONObject message = new JSONObject();
            message.put("content", URLUtil.encode(content));
            message.put("mobile", mobile);

            JSONArray jsonArray = new JSONArray();
            jsonArray.put(message);

            JSONObject messages=new JSONObject();
            messages.put("messages",jsonArray);

            StringEntity entity = new StringEntity(messages.toString(), "UTF-8");
            post.setEntity(entity);
            Long timeStamp=System.currentTimeMillis();
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Authorization", "Bearer " + accessToken);
            post.setHeader("signature", DigestUtils.md5Hex(SMS_ACCOUNT + "|" + SMS_PASSWORD + "|" + timeStamp));
            post.setHeader("timeStamp", timeStamp+"");
            post.setHeader("account", SMS_ACCOUNT);

            System.out.println("send_allHeaders:" + post.getAllHeaders().toString());
            System.out.println("send_entity:" + post.getEntity().toString());
            System.out.println("send_message:" + messages.toString());

            try (CloseableHttpResponse response = client.execute(post)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String result = EntityUtils.toString(response.getEntity());
                System.out.println("响应的状态:" + statusCode);
                System.out.println("响应的内容:" + result);

                if (statusCode == 200) {
                    System.out.println("短信发送成功");
                } else {
                    System.err.println("发送短信失败:" + result);
                }
            }
        }
    }



//    public static void main(String[] args) throws Exception {
//        Long timeStamp=System.currentTimeMillis();
//        System.out.println(timeStamp);
//        System.out.println(StrUtil.utf8Str("测试"));
//        System.out.println( DigestUtils.md5Hex(SMS_ACCOUNT + "|" + SMS_PASSWORD + "|" + timeStamp));
//    }


}
